"""
TTS API客户端示例
正确处理TTS API响应格式
"""
import requests
import json
import os
from typing import Optional, Dict, Any, List


class TTSClient:
    """TTS API客户端"""
    
    def __init__(self, base_url: str = "http://localhost:8021"):
        """初始化客户端"""
        self.base_url = base_url
        self.api_prefix = "/api/v1"
        self.token = None
    
    def set_token(self, token: str):
        """设置认证令牌"""
        self.token = token
    
    def get_headers(self) -> Dict[str, str]:
        """获取请求头"""
        headers = {
            "Content-Type": "application/json"
        }
        if self.token:
            headers["Authorization"] = f"Bearer {self.token}"
        return headers
    
    def synthesize_text(self, text: str, voice_id: Optional[str] = None, 
                        format: str = "wav") -> Dict[str, Any]:
        """合成语音"""
        url = f"{self.base_url}{self.api_prefix}/tts/synthesize"
        
        payload = {
            "text": text,
            "format": format
        }
        
        if voice_id:
            payload["voice_id"] = voice_id
        
        try:
            response = requests.post(url, json=payload, headers=self.get_headers())
            response.raise_for_status()  # 抛出HTTP错误
            
            # 解析响应
            result = response.json()
            
            # 正确访问字段
            if result.get("success"):
                print(f"合成成功: {result.get('message')}")
                print(f"音频URL: {result.get('audio_url')}")
                print(f"音频时长: {result.get('duration')} 秒")
                print(f"音频格式: {result.get('format')}")
                
                # 返回结果
                return result
            else:
                print(f"合成失败: {result.get('message')}")
                return result
                
        except requests.exceptions.HTTPError as e:
            print(f"HTTP错误: {e}")
            try:
                error_data = response.json()
                print(f"API错误: {error_data}")
            except:
                print(f"响应内容: {response.text}")
        except requests.exceptions.ConnectionError:
            print(f"连接错误: 无法连接到服务器 {self.base_url}")
        except requests.exceptions.Timeout:
            print("连接超时")
        except requests.exceptions.RequestException as e:
            print(f"请求错误: {e}")
        except Exception as e:
            print(f"其他错误: {e}")
        
        return {"success": False, "message": "请求失败"}
    
    def download_audio(self, audio_url: str, output_path: str) -> bool:
        """下载音频文件"""
        if not audio_url.startswith("http"):
        # 如果是相对URL，添加基础URL，并修正路径
            if audio_url.startswith('/api/v1/audio/'):
                # 修正路径 - 将 /api/v1/audio/ 改为 /api/v1/tts/audio/
                corrected_url = audio_url.replace('/api/v1/audio/', '/api/v1/tts/audio/')
                full_url = f"{self.base_url}{corrected_url}"
            else:
                full_url = f"{self.base_url}{audio_url}"
        else:
            full_url = audio_url
        
        try:
            # 打印完整URL，用于调试
            print(f"正在尝试下载: {full_url}")
            
            # 添加调试头信息
            headers = self.get_headers()
            print(f"请求头: {headers}")
            
            # 发送请求
            response = requests.get(full_url, headers=headers)
            
            # 检查响应状态码
            if response.status_code == 401 or response.status_code == 403:
                print(f"认证错误 (状态码: {response.status_code}): 需要登录或没有足够权限访问音频文件")
                print("尝试使用认证令牌...")
                # 这里可以添加自动获取认证令牌的代码
                return False
                
            elif response.status_code == 404:
                print(f"音频文件不存在 (状态码: 404)")
                print("可能原因: 文件已被删除、尚未生成或URL路径错误")
                return False
                
            elif response.status_code == 500:
                print(f"服务器内部错误 (状态码: 500)")
                try:
                    error_data = response.json()
                    print(f"错误详情: {error_data.get('error', {}).get('message', '未知错误')}")
                except:
                    print(f"无法解析错误详情: {response.text[:200]}...")
                return False
            
            elif response.status_code != 200:
                print(f"未知错误 (状态码: {response.status_code})")
                print(f"响应内容: {response.text[:200]}...")
                return False
            
            # 检查响应内容类型
            content_type = response.headers.get('Content-Type', '')
            print(f"响应内容类型: {content_type}")
            
            if not content_type.startswith('audio/') and content_type != 'application/octet-stream':
                print(f"警告: 响应不是预期的音频格式 (Content-Type: {content_type})")
                if content_type.startswith('application/json'):
                    try:
                        print(f"JSON响应: {response.json()}")
                    except:
                        pass
            
            # 保存文件
            with open(output_path, 'wb') as f:
                f.write(response.content)
            
            print(f"音频已保存到: {output_path}")
            return True
            
        except requests.exceptions.ConnectionError:
            print(f"连接错误: 无法连接到服务器 {self.base_url}")
            print("请检查服务器是否运行以及端口号是否正确")
            return False
            
        except requests.exceptions.Timeout:
            print("连接超时: 服务器响应时间过长")
            print("可能是服务器负载过高或网络问题")
            return False
            
        except requests.exceptions.RequestException as e:
            print(f"请求错误: {e}")
            return False
            
        except IOError as e:
            print(f"文件写入错误: {e}")
            print(f"请检查输出路径 {output_path} 是否可写")
            return False
            
        except Exception as e:
            print(f"未预期的错误: {e}")
            return False
    
    def get_available_voices(self) -> List[Dict[str, Any]]:
        """获取可用语音列表"""
        url = f"{self.base_url}{self.api_prefix}/tts/voices"
        
        try:
            response = requests.get(url, headers=self.get_headers())
            response.raise_for_status()
            
            result = response.json()
            if "voices" in result:
                return result["voices"]
            return []
        except Exception as e:
            print(f"获取语音列表失败: {e}")
            return []


# 如果直接运行此脚本
if __name__ == "__main__":
    # 创建TTS客户端实例
    client = TTSClient(base_url="http://localhost:8022")
    
    # 合成语音示例
    text = "欢迎使用离线语言播放系统，这是一个测试语音合成的示例。"
    result = client.synthesize_text(text, format="wav")
    
    # 如果合成成功，下载音频
    if result.get("success") and result.get("audio_url"):
        # 创建output目录
        os.makedirs("output", exist_ok=True)
        
        # 下载音频
        client.download_audio(
            result["audio_url"],
            f"output/tts_example.{result.get('format', 'wav')}"
        )
    
    # 获取可用语音示例
    print("\n获取可用语音列表:")
    voices = client.get_available_voices()
    for voice in voices:
        print(f"ID: {voice.get('id')}, 名称: {voice.get('name')}, 语言: {voice.get('language')}")